import "@stdlib/deploy";

message(0x0f8a7ea5) JettonTransfer {
    query_id: Int as uint64; // arbitrary request number
    amount: Int as coins; // amount of jettons to transfer
    destination: Address; // address of the new owner of the jettons
    response_destination: Address; // address where to send a response with confirmation of a successful transfer and the rest of the incoming message Toncoins.
    custom_payload: Cell?; // optional custom payload
    forward_ton_amount: Int as coins; // the amount of nanotons to be sent to the destination address.
    forward_payload: Slice as remaining; // optional custom data that should be sent to the destination address.
}

message(0x7362d09c) JettonTransferNotification {
    query_id: Int as uint64; // arbitrary request number
    amount: Int as coins; // amount of jettons to transfer
    sender: Address; // address of the sender of the jettons
    forward_payload: Slice as remaining; // optional custom payload
}

const TRANSFER_OP: Int = 0x4034a3c0;
const STAKE_OP: Int = 0x6ec9dc65;

// https://github.com/Ludwintor/TonJettonStaking/blob/main/src/staking/staking.tact
contract MyStake with Deployable {
    amount: Int as coins = 0;
    init() {
    }
    receive(msg: JettonTransferNotification){
        let ctx: Context = context();
        let msg_value: Int = ctx.value;
        let forward_payload: Slice = msg.forward_payload;
        let payload: Slice = forward_payload.loadRef().beginParse();
        let op: Int = payload.loadUint(32);
        nativeThrowUnless(10001, op == STAKE_OP);
        if (op == STAKE_OP) {
            self.amount = msg.amount;
            let to: Address = payload.loadAddress();
            self.send_jettons(msg.query_id, msg.amount, to, ctx.sender, msg_value, SendRemainingValue, null);
        }
    }
    
    fun send_jettons(query_id: Int, jetton_amount: Int, destination: Address, jetton_address: Address, msg_value: Int, mode: Int, payload: Cell?) {
        let forward_payload: Cell? = null;
        let forward_ton_amt: Int = 0;
        let value = msg_value;
        if (payload == null) {
            forward_payload = beginCell().storeUint(0, 1).endCell();
        } else {
            forward_payload = beginCell().storeUint(1, 1).storeRef(payload!!).endCell();
            forward_ton_amt = ton("0.03");
        }
        send(SendParameters{
            to: jetton_address,
            value: value,
            bounce: false,
            mode: mode,
            body: JettonTransfer {
                query_id: query_id,
                amount: jetton_amount,
                destination: destination,
                response_destination: destination,
                custom_payload: beginCell().storeUint(0, 1).endCell(),
                forward_ton_amount: forward_ton_amt,
                forward_payload: (forward_payload!!).asSlice()
            }.toCell()
        });
    }
    
    get fun amount(): Int {
        return self.amount;
    }
}
